package com.Server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.Server.Client.SendMag;
import com.Server.DataBase.BanIpTable;
import com.Server.DataBase.OkIpTable;


public class ServerExecutor extends Thread {

	private ServerSocket _server;

	private int _port = 0;

	private static final Logger _log = Logger.getLogger(ServerExecutor.class.getName());

	private boolean _msg ;

	public ServerExecutor(final int port) {
		try {
			this._port = port;
			this._server = new ServerSocket(this._port);
		} catch (final SocketTimeoutException e) {
			_log.log(Level.SEVERE ,"連線超時:(" + this._port + ")", e);

		} catch (final IOException e) {
			_log.log(Level.SEVERE ,"IP位置加載錯誤 或 端口位置已被佔用:(" + this._port + ")", e);

		} finally {
			if(!_msg){
				_log.info("[D] " + this.getClass().getSimpleName() + " 開始監聽服務端口:(" + this._port + ")");
				_msg = true;
			}
		}
	}


	@Override
	public void run() {

		try {
			while (this._server !=null) {
				if(Config.SERVER_START == false){
					break;
				}
				Socket socket = null;
				try {
					socket = this._server.accept();
					if (socket != null) {
						final String host = socket.getInetAddress().getHostAddress();
						String msg = "ok";
						if(BanIpTable.getInstance().isBannedIp(host)){
							msg = "close";
						}else if(!OkIpTable.get().isOkIp(host)
								&& !OkIpTable.get().isOnline(host)){
						}
						SendMag st = new SendMag(socket , msg , host);
						GeneralThreadPool.getInstance().execute(st);
					}
				} catch (final SecurityException e) {
				}
			}
		} catch (final IOException e) {
			//			_log.log(Level.SEVERE , e.getLocalizedMessage() , e);
		} finally {
			final String lanInfo = "[D] " + this.getClass().getSimpleName() + " 服務器核心關閉監聽端口(" + this._port + ")";
			_log.info(lanInfo);
		}
	}
	/**
	 * 停止監聽
	 */
	public void stopEcho() {
		try {
			if (this._server != null) {
				StreamUtil.close(this._server);
				StreamUtil.interrupt(this);
				this._server = null;
			}

		} catch (final Exception e) {
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);

		} finally {

		}
	}


	/**
	 * 啟動監聽
	 * @throws IOException
	 */
	public void stsrtEcho() throws IOException {
		GeneralThreadPool.getInstance().execute(this);
	}



}
